#!/bin/bash

echo "正在启动服务..."

# 检测操作系统类型和架构
OS_TYPE=$(uname -s)
ARCH=$(uname -m)

case "$OS_TYPE" in
    "Darwin")    # macOS
        if [ "$ARCH" = "arm64" ]; then
            MINICONDA_FILE="Miniconda3-py39_4.12.0-MacOSX-arm64.sh"
        else
            MINICONDA_FILE="Miniconda3-py39_4.12.0-MacOSX-x86_64.sh"
        fi
        ;;
    "Linux")     # Linux
        if [ "$ARCH" = "aarch64" ]; then
            MINICONDA_FILE="Miniconda3-py39_4.12.0-Linux-aarch64.sh"
        else
            MINICONDA_FILE="Miniconda3-py39_4.12.0-Linux-x86_64.sh"
        fi
        ;;
    *)
        echo "不支持的操作系统类型: $OS_TYPE"
        exit 1
        ;;
esac

# 检查是否已安装便携版 Python
if [ ! -f "python_env/bin/python3" ]; then
    echo "Python环境未检测到，正在下载便携版Python..."
    
    # 定义镜像源数组
    MIRRORS=(
        "https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda"
        "https://mirrors.aliyun.com/anaconda/miniconda"
        "https://repo.anaconda.com/miniconda"
    )
    
    # 创建临时目录用于下载安装脚本
    TEMP_DIR=$(mktemp -d)
    INSTALLER_PATH="${TEMP_DIR}/${MINICONDA_FILE}"
    
    # 遍历镜像源尝试下载
    for mirror in "${MIRRORS[@]}"; do
        echo "尝试从 ${mirror} 下载..."
        if wget --no-check-certificate -O "${INSTALLER_PATH}" "${mirror}/${MINICONDA_FILE}"; then
            break
        fi
    done
    
    # 检查下载是否成功
    if [ ! -f "${INSTALLER_PATH}" ]; then
        echo "Python下载失败！请检查网络连接。"
        rm -rf "${TEMP_DIR}"
        exit 1
    fi
    
    # 添加执行权限并安装Python
    echo "正在安装Python环境..."
    chmod +x "${INSTALLER_PATH}"
    bash "${INSTALLER_PATH}" -b -p "$(pwd)/python_env" || {
        echo "Python安装失败！"
        rm -rf "${TEMP_DIR}"
        exit 1
    }
    
    # 清理临时文件
    rm -rf "${TEMP_DIR}"
    
    # 安装依赖并显示进度
    echo "正在安装项目依赖..."
    python_env/bin/pip3 install --progress-bar on -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple || {
        echo "依赖安装失败！尝试使用备用镜像..."
        python_env/bin/pip3 install --progress-bar on -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ || {
            echo "依赖安装失败！"
            exit 1
        }
    }
    
    echo "Python环境安装完成！"
fi

# 使用安装的Python启动服务器
echo "正在启动Web服务器..."
python_env/bin/python3 webapp.py

# 如果发生错误，显示错误信息并等待
if [ $? -ne 0 ]; then
    echo "服务启动失败！请检查错误信息。"
    read -p "按回车键继续..."
fi 